﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Documents
//  File name:	MultiLookupFieldWithPickerControl.cs
//  Developer:	Solomatov Igor
//  Created:	16.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using System.Collections;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

// ReSharper disable CheckNamespace

namespace Smart.Documents.Fields.LookupFieldWithPicker
// ReSharper restore CheckNamespace
{
	public class MultiLookupWithPickerControl : LookupFieldWithPickerControl
	{
		public override object Value
		{
			get
			{
				EnsureChildControls();

				var resolvedEntities = lookupEditor.ResolvedEntities;

				if (resolvedEntities.Count == 0)
					return null;

				var lookups = new SPFieldLookupValueCollection();

				lookups.AddRange(
					resolvedEntities.Cast<PickerEntity>().Select(
						entity => new SPFieldLookupValue(int.Parse(entity.Key), entity.DisplayText)));

				return lookups;
			}
			set
			{
				EnsureChildControls();
				SetFieldControlValue(value);
			}
		}

		private void SetFieldControlValue(object value)
		{
			var lookupFieldPicker = (LookupFieldWithPicker) Field;

			lookupEditor.Entities.Clear();

			var list = new ArrayList();

			if (ControlMode == SPControlMode.New && lookupEditor.Entities.Count == 0
			    && String.IsNullOrEmpty(lookupFieldPicker.CustomDefaultValue) == false)
			{
				var strValue = ParseDefaultValue(lookupFieldPicker.CustomDefaultValue);

				if (strValue == null)
					return;

				var defaultEntity = lookupEditor.ValidateEntity(new PickerEntity {Key = strValue, DisplayText = strValue});

				if (defaultEntity != null)
					list.Add(defaultEntity);
			}
			else
			{
				var lookupValues = value as SPFieldLookupValueCollection;

				foreach (var lookupValue in lookupValues)
				{
					var entity = lookupEditor.GetEntityById(lookupValue.LookupId);

					if (entity != null)
					{
						list.Add(entity);
					}
				}
			}

			lookupEditor.UpdateEntities(list);
		}
	}
}